<template>
  <div class="sim-var-table">
    <table-header :indragging="indragging" />

    <div class="sim-var-table-body">
      <div
        v-for="(row, index) in rows"
        :key="row[primaryKey] || index"
        class="body-group"
      >
        <table-row :row="row"
                   :index="index"
                   :total="rows.length"
                   :level="1"
                   @toggle-expand="toggleExpand"
                   @contextmenu="onContextmenu" />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, provide, useSlots } from "vue";
import { VarTableColumn } from "@/constants/types";

import TableHeader from "./TableHeader.vue";
import TableRow from "./TableRow.vue";

const props = withDefaults(
  defineProps<{
    indragging?: boolean;
    columns: VarTableColumn[];
    rows: any[];
    primaryKey?: string;
    level?: number;
  }>(),
  {
    indragging: true,
    primaryKey: "id",
    level: 1,
  }
);

const emit = defineEmits<{
  (e: "toggleExpand", expand: boolean, row: any): void;
  (
    e: "contextmenu",
    evt: MouseEvent,
    row: any,
    item: any,
    col: VarTableColumn
  ): void;
}>();

const cols = computed(() => {
  return props.columns.filter((col) => !col.hidden);
});
provide("columns", cols);
provide("rows", props.rows);

const slots = useSlots();
provide("slots", slots);

const toggleExpand = (row: any) => {
  emit("toggleExpand", row.expand, row);
};

const onContextmenu = (
  e: MouseEvent,
  row: any,
  item: any,
  col: VarTableColumn
) => {
  emit("contextmenu", e, row, item, col);
};
</script>

<style lang="scss">
@import "@/assets/css/app.scss";

.sim-var-table {
  display: grid;
  grid-template-rows: auto 1fr;
  height: 100%;
}

.sim-var-table-body {
  display: flex;
  flex-direction: column;
  background-color: #fff;
  overflow-y: auto;
  overflow-x: hidden;

  .body-group {
    position: relative;
    border-bottom: 1px solid $black-e0;
  }
}
</style>
